<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>井字棋</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    {% load static %}
    <!--suppress HtmlUnknownTarget -->
    <script src="{% static 'js/navbar.js' %}"></script>
    <!--suppress HtmlUnknownTarget -->
    <link rel="stylesheet" href="{% static 'css/navbar.css' %}">
    <style>
        body {
            text-align: center;
            font-family: Arial, sans-serif;
        }

        .board {
            display: grid;
            grid-template-columns: repeat(3, 100px);
            gap: 5px;
            justify-content: center;
        }

        .cell {
            width: 100px;
            height: 100px;
            font-size: 2em;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid #333;
            cursor: pointer;
        }

        .cell.X {
            cursor: not-allowed;
            color: blue;
            font-weight: bold;
        }

        .cell.O {
            cursor: not-allowed;
            color: green;
            font-weight: bold;
        }

        .message {
            margin-top: 20px;
            font-size: 1.2em;
        }

        .restart {
            margin-top: 10px;
            padding: 10px 20px;
            font-size: 1em;
            cursor: pointer;
            background-color: blue;
            color: white;
            border: none;
        }

        .win-line {
            position: absolute;
            width: 0;
            height: 5px;
            background-color: red;
            transform-origin: left;
        }
    </style>
</head>
<body>
{% include "includes/navbar.html" %}
<span style="background: palegoldenrod; padding: 10px">登录后，游戏结束可获得金币：胜利：10000，平局：5，失败：0</span>
<h1>井字棋</h1>
<div class="board">
    <div class="cell X"></div>
    <div class="cell O"></div>
</div>
<button class="restart">重新开始</button>
<div class="message"></div>
<script>
    let key = Math.random();
    let board = Array(9).fill(0);
    let isOver = false;
    const winLine = $('<div class="win-line"></div>').appendTo('.board');

    function refreshBoard() {
        $('.board').empty().append(winLine);
        board.forEach((value, index) => {
            let c = [' ', 'O', 'X'][value];
            $('.board').append(`<div class='cell ${c}' data-index='${index}'>${c}</div>`);
        });
    }


    function drawWinLine(a, b, c) {
        let positions = [a, b, c].map(i => $(`.cell[data-index='${i}']`).position());
        let start = positions[0], end = positions[2];
        let dx = end.left - start.left, dy = end.top - start.top;
        let length = Math.sqrt(dx * dx + dy * dy);
        let angle = Math.atan2(dy, dx) * 180 / Math.PI;
        winLine.css({
            top: start.top + 50 + 'px',
            left: start.left + 50 + 'px',
            width: length + 'px',
            transform: `rotate(${angle}deg)`,
        });
    }

    function refreshWinLine() {
        const lines = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ];
        for (const [a, b, c] of lines) {
            if (board[a] && board[a] === board[b] && board[a] === board[c]) {
                drawWinLine(a, b, c);
                return;
            }
        }
    }

    // .cell是动态元素，需要用这种写法绑定到document上，如果用$('.cell').click的写法会绑定在元素上，移除或创建元素就没了
    $(document).on("click", ".cell", function () {
        let p = $(this).data("index");
        if (isOver || board[p]) return;
        board[p] = 1;

        let formData = new FormData();
        formData.append('key', key);
        formData.append('next', `${+p + 1}`);

        fetch('{% url "tic_tac_toe" %}', {
            method: 'POST',
            body: formData,
        }).then(response => response.json())
            .then(data => {
                if (data['board']) {
                    board = data['board'].flat();
                }
                if (data['next'] && data['next'] !== -1) {
                    let e = data['next'] - 1;
                    board[e] = 2;
                    refreshBoard();
                }
                if (data['victor'] !== undefined) {
                    refreshBoard();
                    refreshWinLine();
                    refreshCoin();
                    $('.cell').css('cursor', 'not-allowed');
                    $('.message').text(data['message']);
                    isOver = true;
                }
                if (data['error']) {
                    $('.message').text(data['error']);
                }
            });
    });

    function endGame() {
        let formData = new FormData();
        formData.append('key', key);
        formData.append('next', '-1');

        fetch('{% url "tic_tac_toe" %}', {
            method: 'POST',
            body: formData
        });
    }

    $(".restart").click(function () {
        endGame();
        key = Math.random();
        board = Array(9).fill(0);
        isOver = false;
        $('.message').text('');
        winLine.css({width: 0});
        refreshBoard();
    });

    window.addEventListener('beforeunload', function (event) {
        // 阻止默认行为
        event.preventDefault();

        endGame();
    });

    refreshBoard();
</script>
</body>
</html>